package com.ship.dispatch.service.fob.impl;
/**
 *@title SpFobQrxzgServiceImpl
 *@description fob001 确认卸载港、卸载窗口 / 与DES买方确认卸载信息 fob004
 *@author yl
 *@create 2023/12/16 0016
 */

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ship.common.core.exception.BusException;
import com.ship.common.core.utils.DateUtil;
import com.ship.common.core.utils.StringUtils;
import com.ship.common.core.web.domain.BaseResultCode;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.dispatch.bean.SpArrangeSchemeDetail;
import com.ship.dispatch.bean.SpDispatchSchemeExecute;
import com.ship.dispatch.bean.SpPortInformation;
import com.ship.dispatch.bean.fob.*;
import com.ship.dispatch.bpm.utils.JsonUtils;
import com.ship.dispatch.bpm.utils.TemplateParamUtils;
import com.ship.dispatch.bpm.vo.ManageEntityVo;
import com.ship.dispatch.mapper.SpPortInformationMapper;
import com.ship.dispatch.mapper.fob.SpFobMfqrzzxxMapper;
import com.ship.dispatch.mapper.fob.SpFobQrxzgMapper;
import com.ship.dispatch.service.SpArrangeSchemeDetailService;
import com.ship.dispatch.service.SpDispatchSchemeExecuteService;
import com.ship.dispatch.service.fob.SpFobFileRecordService;
import com.ship.dispatch.service.fob.SpFobQrxzgService;
import com.ship.dispatch.service.fob.SpFobTemplateService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SpFobQrxzgServiceImpl extends FobBaseServiceImpl<SpFobQrxzgMapper, SpFobQrxzg> implements SpFobQrxzgService {

    @Autowired(required = false)
    SpFobQrxzgMapper mapperapper;

    @Autowired
    SpFobFileRecordService spFobFileRecordService;
    @Autowired
    SpFobTemplateService spFobTemplateService;
    @Autowired
    SpDispatchSchemeExecuteService schemeDetailService;
    @Autowired(required = false)
    SpFobMfqrzzxxMapper spFobMfqrzzxxMapper;
    @Autowired(required = false)
    SpPortInformationMapper spPortInformationMapper;

    @Autowired
    SpArrangeSchemeDetailService spArrangeSchemeDetailService;
    @Override
    public void updateEntity(ManageEntityVo manageEntityVo, String json) {
        SpFobQrxzg object = JsonUtils.jsonToObject(json,SpFobQrxzg.class);
        SpFobQrxzg his = mapperapper.selectOne(new LambdaQueryWrapper<SpFobQrxzg>().eq(SpFobQrxzg::getProceeInstanceId,manageEntityVo.getProcessInstanceId()).ne(SpFobQrxzg::getStatus,-2));
        if(manageEntityVo.getOperationType()==1) {
            object.setStatus(1);
        }
        if(his==null){ // 新增
            object.setSchemeDetailId(manageEntityVo.getSchemeDetailId());
            object.setTaskId(manageEntityVo.getTaskId());
            object.setProceeInstanceId(manageEntityVo.getProcessInstanceId());
            mapperapper.insert(object);
        }else { // 修改
            object.setId(his.getId());
            BeanUtils.copyProperties(object,his);
            mapperapper.updateById(his);
            // 处理多余文件记录
            SpDispatchSchemeExecute execute = schemeDetailService.getExceuteByInstanceId(manageEntityVo.getProcessInstanceId());
            if(execute!=null && StringUtils.isNotEmpty(his.getExpectedUnloading())){
                SpArrangeSchemeDetail spDispatchSchemeDetail = new SpArrangeSchemeDetail();
                spDispatchSchemeDetail.setId(execute.getArrangeSchemeDetailId());
                spDispatchSchemeDetail.setRealityLoadingPort(his.getExpectedUnloading());
                spArrangeSchemeDetailService.updateById(spDispatchSchemeDetail);
            }
            List<String> ids = new ArrayList<>();
            if((his.getFiels()!=null && his.getFiels().length()>0)){
                String temp = his.getFiels();
                String[] fieldIds = temp.split(",");
                ids =  Arrays.stream(fieldIds).collect(Collectors.toList());
            }
            spFobFileRecordService.deleteOtherFileRecor(his.getId(),ids);
        }
    }

    @Override
    public SpFobBaseBean getBaseBeanByInstanceId(String id) {
        return mapperapper.selectOne(new LambdaQueryWrapper<SpFobQrxzg>().eq(SpFobQrxzg::getProceeInstanceId,id).ne(SpFobQrxzg::getStatus,-2));
    }
    @Override
    public void  saveEntity(SpFobBaseBean bean){
        SpFobQrxzg spFobZzgcjr = new SpFobQrxzg();
        BeanUtils.copyProperties(bean,spFobZzgcjr);
        this.save(spFobZzgcjr);
    }

    @Override
    public void updateEntityById(SpFobBaseBean bean) {
        SpFobQrxzg spFobZzgcjr = new SpFobQrxzg();
        BeanUtils.copyProperties(bean,spFobZzgcjr);
        this.updateById(spFobZzgcjr);
    }


    @Override
    public Object getFormData(String id,Long serviceId) {
        SpFobQrxzg spFobZzgcjr = null;
        if(serviceId!=null){
            spFobZzgcjr = mapperapper.selectById(serviceId);
        }else {
            spFobZzgcjr = mapperapper.selectOne(new LambdaQueryWrapper<SpFobQrxzg>().eq(SpFobQrxzg::getProceeInstanceId,id).ne(SpFobQrxzg::getStatus,-2));
        }
        if(spFobZzgcjr==null){
            return null;
        }
        SpDispatchSchemeExecute execute = schemeDetailService.getExceuteByInstanceId(spFobZzgcjr.getProceeInstanceId());
        if(StringUtils.isEmpty(spFobZzgcjr.getExpectedUnloading())){
            spFobZzgcjr.setExpectedUnloading(execute.getExpectedUnloadingPort());
        }
        if(StringUtils.isEmpty(spFobZzgcjr.getExpectedUnloadingPort()) && execute.getExpectedUnloadingWindow()!=null){
            spFobZzgcjr.setExpectedUnloadingPort(DateUtil.date2Str(execute.getExpectedUnloadingWindow(),"yyyy-MM-dd HH:mm:ss"));
        }
        Map<String,Object> map = JsonUtils.jsonToMap(JsonUtils.objectToJson(spFobZzgcjr), Object.class);
        if(StringUtils.isNotBlank(spFobZzgcjr.getFiels())){
            String[] ids = spFobZzgcjr.getFiels().split(",");
            List<Long> resId = new ArrayList<>();
            for(String tempId:ids){
                if (StringUtils.isNotBlank(tempId)) {
                    resId.add(Long.parseLong(tempId));
                }
            }
            List<SpFobFileRecord> spFobFileRecordList =  spFobFileRecordService.listByIds(resId);
            map.put("fiels",spFobFileRecordList);
        }
        if (execute.getExpectedUnloadingPort()!=null && spFobZzgcjr.getPort() == null){
            map.put("port",execute.getExpectedUnloadingPort());
        }
        return map;
    }


    @Override
    public String  getTemplateParam(ManageEntityVo manageEntityVo) {
        ObjectNode json = manageEntityVo.getData();
        SpFobQrxzg spFobZzgcjr = JsonUtils.jsonToObject(JsonUtils.objectToJson(json),SpFobQrxzg.class);
        String  templateId = spFobZzgcjr.getTemplateId();
        if(templateId==null){
            throw  new BusException("请选模板后再生成模板正文", BaseResultCode.GENERAL_ERROR);
        }
        SpFobTemplate spFobTemplate = spFobTemplateService.getById(templateId);
        if(spFobTemplate == null){
            throw  new BusException("当前模板不存在，请联系管理员处理", BaseResultCode.GENERAL_ERROR);
        }
        // 调度方案信息
        SpDispatchSchemeExecute schemeDetail = schemeDetailService.getExceuteByInstanceId(manageEntityVo.getProcessInstanceId());
        Map<String,String> map = new HashMap<>();
        if(schemeDetail!=null){
            Map<String,String> tempMap = JsonUtils.jsonToMap(JsonUtils.objectToJson(schemeDetail),String.class);
            for(String key:tempMap.keySet()){
                map.put("spDispatchSchemeDetail."+key,tempMap.get(key));
            }
        }
        if(spFobZzgcjr.getMaCronId()!=null){ // 获取合同
            Map<String,String> tempMap = spFobMfqrzzxxMapper.getNaCroInfo(spFobZzgcjr.getMaCronId());
            for(String key:tempMap.keySet()){
                String tempKey = JsonUtils.toCamelCase(key);
                map.put("conResourceMain."+tempKey,tempMap.get(key));
            }
            if("1".equals(tempMap.get("trade_body"))){
                map.put("temp2","Hong kong");
                map.put("temp1","CNOOC Gas and Power Trading& Marketing Limited");
                map.put("temp3","GPTM");
            }else {
                map.put("temp2","Singapore");
                map.put("temp1","CNOOC Gas and Power Singapore Trading& Marketing Pte. Ltd");
                map.put("temp3","SG");
            }
        }
        SpPortInformation spPortInformation  = null;
        if(spFobZzgcjr.getExpectedUnloading()!=null){ // 获取港口信息
            spPortInformation = spPortInformationMapper.selectById(spFobZzgcjr.getExpectedUnloading());
        }
        if(spPortInformation==null){
            spPortInformation = spPortInformationMapper.selectOne(new LambdaQueryWrapper<SpPortInformation>()
                    .eq(SpPortInformation::getPortNameEnglish,schemeDetail.getExpectedUnloadingPort())
                    .or().eq(SpPortInformation::getPortNameChinese,schemeDetail.getExpectedUnloadingPort())
                    .last("LIMIT 1")
            );
        }
        if(spPortInformation!=null){
            map.put("spPortInformation.portCountry",spPortInformation.getPortCountry());
            map.put("spPortInformation.portNameEnglish",spPortInformation.getPortNameEnglish());
        }else{
            map.put("spPortInformation.portCountry","");
            map.put("spPortInformation.portNameEnglish","");
        }        // 当前业务表单信息
        if(json!=null){
            Map<String,String> tempMap = JsonUtils.jsonToMap(JsonUtils.objectToJson(json),String.class);
            for(String key:tempMap.keySet()){
                map.put("spFobQrxzg."+key,tempMap.get(key));
            }
        }
        map.put("spFobQrxzg.sendRecipient", SecurityUtils.getUsername());
        String  template = TemplateParamUtils.processDynamicParams(spFobTemplate.getContent(),map);
        return template;
    }

    @Override
    public SpFobQrxzg findData(String schemeId) {
        SpFobQrxzg spFobZzgcjr = mapperapper.selectOne(new LambdaQueryWrapper<SpFobQrxzg>().eq(SpFobQrxzg::getProceeInstanceId,schemeId).ne(SpFobQrxzg::getStatus,-2));
        return spFobZzgcjr;
    }

    @Override
    public List<Long> findServieData(String processInstanceId){
        List<SpFobQrxzg> spFobBaseBeans =  mapperapper.selectList(new LambdaQueryWrapper<SpFobQrxzg>().eq(SpFobQrxzg::getProceeInstanceId,processInstanceId).orderByDesc(SpFobQrxzg::getCreateDate));
        List<Long> list = spFobBaseBeans.stream().map(SpFobBaseBean::getId).collect(Collectors.toList());
        return list;
    }
}
